import { ref, reactive } from 'vue';
import { ElNotification } from 'element-plus';
import { getUserRoles, addUser, getRoles, addUserRoles } from '@/axios/api/acl/user';

export default function () {
    interface rolesType {
        role_id: number;
        role_name: string;
    }

    // 所有角色
    const allRoles = ref<rolesType[]>([]);
    // 所有角色名称
    const roleNames = ref<string[]>([]);

    // 已选择角色
    const selectedRoles = ref<string[]>([]);

    // 用户列表
    const tableData = ref([]);

    let useradd_data = reactive({
        id: '',
        username: '',
        pwd: '',
        fullname: '',
    })
    // 抽屉
    let dialog = ref(false); // 是否显示抽屉

    // 搜索框
    let username = ref('');

    // 当前页数
    let currentPage4 = ref(1);
    // 每页显示条数
    let pageSize4 = ref(10);
    // 总条数
    let total4 = ref(0);
    // 获取用户列表
    const getUsers = async () => {
        tableData.value = [];
        try {
            let res: any = await getUserRoles({
                username: username.value,
                page: currentPage4.value,
                size: pageSize4.value
            });
            tableData.value = res.data;
            total4.value = res.total;
        } catch (error: any) {
            ElNotification({
                title: 'Error',
                message: error,
                type: 'error',
            })
        }
    }
    // 每页显示条目个数改变时触发
    const getHasUser = () => {
        getUsers();
    }
    // 当前页数改变时触发
    const handler = () => {
        getUsers();
    }

    // 搜索
    const handleSearch = async () => {
        getUsers();
    }
    // 重置
    const handleReset = () => {
        username.value = '';
    }

    // 编辑
    const handleEdit = () => {
        dialog.value = true;
    }
    // 删除
    const handleDelete = async (_index: number) => {
        ElNotification({
            title: 'Error',
            message: '该功能暂未实现',
            type: 'error',
        })
    }

    // 添加用户
    const handleAdd = () => {
        dialog.value = true;
    }
    // 添加用户提交
    const handleAddsubmit = async () => {
        try {
            let res: any = await addUser(useradd_data);
            ElNotification({
                title: 'Success',
                message: res.msg,
                type: 'success',
            });
            useradd_data.id = '';
            useradd_data.username = '';
            useradd_data.fullname = '';
            useradd_data.pwd = '';
            dialog.value = false;
            currentPage4.value = 1;
            getUsers();
        } catch (error: any) {
            ElNotification({
                title: 'Error',
                message: error,
                type: 'error',
            })
        }
    }
    // 批量删除
    const handleDeleteAll = () => {
        console.log('delete all');

    }

    // 抽屉表单校验

    const rusername1 = (_rule: any, value: any, callback: any) => {
        if (/^\d+$/.test(value)) {
            callback(new Error('账号不能为纯数字'))
        } else if (value === '') {
            callback(new Error('请输入账号'))
        } else {
            callback() //通过
        }
    }
    const rusername2 = (_rule: any, value: any, callback: any) => {
        // 判断value是否在tableData中
        let flag = false;
        tableData.value.forEach((item: any) => {
            if (item.username.toLowerCase() === value.toLowerCase()) {
                flag = true;
                return;
            }
        });

        if (flag) {
            callback(new Error('账号已存在'))
        } else {
            callback() //通过
        }
    }
    const rfullname = (_rule: any, value: any, callback: any) => {
        if (/^\d+$/.test(value)) {
            callback(new Error('用户名不能为纯数字'))
        } else if (value === '') {
            callback(new Error('请输入用户名'))
        } else {
            callback() //通过
        }
    }
    const rpwd = (_rule: any, value: any, callback: any) => {
        if (/^\d+$/.test(value)) {
            callback(new Error('密码不能为纯数字'))
        } else if (value === '') {
            callback(new Error('请输入密码'))
        } else {
            callback() //通过
        }
    }
    const rules = {
        username: [
            { validator: rusername1, trigger: 'change' },
            { validator: rusername2, trigger: 'blur' }
        ],
        fullname: [
            { validator: rfullname, trigger: 'change' }
        ],
        pwd: [
            { validator: rpwd, trigger: 'change' }
        ]

    }

    // 分配角色
    interface roleType {
        UserID: number;
        UserName: string;
        roles: number[];
    }
    let role_data = reactive<roleType>({
        UserID: 0,
        UserName: '',
        roles: []
    })

    let dialog_role = ref(false) // 是否显示分配角色抽屉

    // 弹出分配角色
    const handleRole = async (row: any) => {
        try {
            let res = await getRoles();
            allRoles.value = res.data; // 所有角色
            roleNames.value = allRoles.value.map((item: any) => item.role_name); // 所有角色名称
            selectedRoles.value = row.roles ? row.roles.split(',') : []; // 已选择角色
            role_data.UserID = row.UserID; // 用户id
            role_data.UserName = row.UserName; // 用户姓名
            dialog_role.value = true; // 显示分配角色抽屉
        } catch (error: any) {
            roleNames.value = [];
            selectedRoles.value = [];
            dialog_role.value = false;
            ElNotification({
                title: 'Error',
                message: error,
                type: 'error',
            })
        }
    }


    const checkAll = ref(false) // 全选
    const isIndeterminate = ref(true) // 半选


    // 全选/半选
    const handleCheckAllChange = (val: boolean) => {
        selectedRoles.value = val ? roleNames.value : []
        isIndeterminate.value = false
    }
    // 已选中角色
    const handleCheckedCitiesChange = (value: string[]) => {
        const checkedCount = value.length
        checkAll.value = checkedCount === roleNames.value.length
        isIndeterminate.value = checkedCount > 0 && checkedCount < roleNames.value.length
    }

    // 提交分配角色
    const submitRole = async () => {
        if (selectedRoles.value.length === 0) {
            ElNotification({
                title: 'Error',
                message: '请选择角色',
                type: 'error',
            })
            return;
        }
        role_data.roles = selectedRoles.value.map(roleName => {
            let role: any = allRoles.value.find(item => item.role_name === roleName);
            return role.role_id;
        });

        try {
            let res = await addUserRoles(role_data)
            ElNotification({
                title: 'Success',
                message: res.msg,
                type: 'success',
            });
            dialog_role.value = false;
            currentPage4.value = 1;
            getUsers();
        } catch (error: any) {
            ElNotification({
                title: 'Error',
                message: error,
                type: 'error',
            })
        }
    }

    return {
        tableData,
        useradd_data,
        dialog,
        username,
        currentPage4,
        pageSize4,
        total4,
        rules,
        role_data,
        dialog_role,
        allRoles,
        roleNames,
        selectedRoles,
        checkAll,
        isIndeterminate,
        getHasUser,
        handler,
        handleSearch,
        handleReset,
        handleRole,
        handleEdit,
        handleDelete,
        handleAdd,
        handleDeleteAll,
        getUsers,
        handleAddsubmit,
        handleCheckAllChange,
        handleCheckedCitiesChange,
        submitRole
    }
}